<template>
  <div class="app-container">
    <el-row :gutter="30">
      <el-col :span="5" style="border-right:1px solid #dcdfe6;height:700px">
        <el-input
          placeholder="输入组织名称"
          size="small"
          style="width:110px;margin-bottom:10px"
          @keyup.enter.native="searchTreeData"
          v-model="treeSearchInputValue"
          clearable>
        </el-input>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="searchTreeData">搜索</el-button>
        <el-tree :data="treeData" :props="defaultProps" @node-click="handleNodeClick" empty-text="暂无数据"
                 :default-expanded-keys="defaultExpandedKeys" :load="loadChildren" lazy highlight-current
                 node-key="id"></el-tree>
      </el-col>
      <el-col :span="19">
        <div style="margin-top:10px">
          <el-button icon="el-icon-plus" type="primary" size="mini" @click="addData"
                     v-if="p1">新增
          </el-button>
          <el-button icon="el-icon-close" type="danger" size="mini" @click="deleteAny"
                     v-if="p4">
            删除
          </el-button>
        </div>
        <div class="query-form">
          <el-form ref="tableSearchParam" :model="tableSearchParam" label-width="50px" :inline="true">
            <!--<el-form-item label="父组织名称" label-width="90px">-->
            <!--<el-input v-model="tableSearchParam.name" style="width:200px" size="small"></el-input>-->
            <!--</el-form-item>-->
            <el-form-item label="组织编码" label-width="70px">
              <el-input v-model="tableSearchParam.code" style="width:200px" size="small"></el-input>
            </el-form-item>
            <el-form-item label="组织名称" label-width="90px">
              <el-input v-model="tableSearchParam.name" style="width:200px" size="small"></el-input>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="listTableData" icon="el-icon-search" size="small">查询</el-button>
            </el-form-item>
          </el-form>
        </div>
        <br/>
        <el-table
          :data="tableData"
          border
          empty-text="暂无数据"
          style="width: 100%"
          @selection-change="handleSelectionChange">
          <el-table-column
            type="selection"
            width="35">
          </el-table-column>
          <el-table-column
            label="上级组织"
            property="pname"
            width="120">
          </el-table-column>
          <el-table-column
            label="组织编码"
            property="code"
            width="120">
          </el-table-column>
          <el-table-column
            label="组织名称"
            property="name"
            width="120">
          </el-table-column>
          <el-table-column
            property="createdTime"
            label="创建时间"
            width="150">
          </el-table-column>
          <el-table-column label="操作">
            <template slot-scope="scope">
              <el-button
                size="mini"
                icon="el-icon-edit"
                type="success"
                v-if="p2"
                @click="editData(scope.$index, scope.row)">编辑
              </el-button>
              <el-button
                size="mini"
                icon="el-icon-lemone-user_role"
                type="warning"
                v-if="p3"
                @click="allocateRole(scope.$index, scope.row)">分配角色
              </el-button>
              <el-button
                size="mini"
                type="danger"
                icon="el-icon-close"
                v-if="p4"
                @click="handleDelete(scope.$index, scope.row)">删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
        <div class="page">
          <el-pagination
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :current-page=this.currentPage
            :page-sizes="[10, 20, 30, 40]"
            :page-size=this.pageSize
            layout="total, sizes, prev, pager, next, jumper"
            :total=this.total>
          </el-pagination>
        </div>
      </el-col>
    </el-row>
    <el-dialog :title="actionType=='add'?'新增组织':'修改组织'" :visible.sync="dialogFormVisible" top="10vh">
      <el-form :model="formData" style="width:400px" :rules="rules" ref="ruleForm">
        <el-form-item label="上级组织" :label-width="formLabelWidth">
          <el-select v-model="formData.parentId" placeholder="请选择" no-data-text="暂无数据" @change="pOrganizationChange">
            <el-option
              v-for="item in allData"
              :key="item.id"
              :label="item.label"
              :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="组织编码" :label-width="formLabelWidth" prop="code">
          <el-input v-model="formData.code" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="组织名称" :label-width="formLabelWidth" prop="name">
          <el-input v-model="formData.name" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="排序码" :label-width="formLabelWidth">
          <el-input v-model="formData.sort" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="组织描述" :label-width="formLabelWidth">
          <el-input type="textarea" v-model="formData.description" auto-complete="off" :rows="6"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="handleAdd" v-if="actionType=='add'" :loading="loading">保存</el-button>
        <el-button type="primary" @click="handleEdit" v-else :loading="loading">修改</el-button>
      </div>
    </el-dialog>
    <el-dialog title="分配角色" :visible.sync="dialogRoleFormVisible" top="10vh">
      <div style="margin-left: 50px">
        <el-transfer v-model="selectRole" :data="noSelectRole" :titles="title"
                     :props="{key: 'id',label: 'name'}"></el-transfer>
      </div>

      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogRoleFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="handleAllocateRole" :loading="loading">保存</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<style lang="scss">
  .page {
    text-align: center;
    margin-top: 20px;
  }

  .query-form {
    border-bottom: 1px solid #ebeef5;
    padding-top: 25px;
  }
</style>

<script>

  import organizationApi from '@/api/organizationApi'
  import roleApi from '@/api/roleApi'
  import organization2roleApi from '@/api/organization2roleApi'

  export default {
    created() {
      this.p1 = this.permissionValid.validAction(this.permissionValid.permissionRule.organization.addOrganization)
      this.p2 = this.permissionValid.validAction(this.permissionValid.permissionRule.organization.updateOrganization)
      this.p3 = this.permissionValid.validAction(this.permissionValid.permissionRule.organization2role.updateOrganizationRole)
      this.p4 = this.permissionValid.validAction(this.permissionValid.permissionRule.organization.removeOrganization)
      this.initData()
    },
    data() {
      return {
        p1: false,
        p2: false,
        p3: false,
        p4: false,
        title: ['未分配角色', '已分配角色'],
        noSelectRole: [],
        selectRole: [],
        allData: [],
        tableData: [],
        currentPage: 1,
        pageSize: 10,
        total: 0,
        tableSearchParam: {},
        treeData: [],
        treeSearchInputValue: '',
        treeSearchParam: {
          name: '',
          code: ''
        },
        defaultProps: {
          children: 'children',
          label: 'label',
          isLeaf: 'leaf'
        },
        dialogFormVisible: false,
        formLabelWidth: '80px',
        formData: {
          parentId: '',
          parentPath: '',
          code: '',
          name: '',
          sort: '',
          description: ''

        },
        loading: false,
        actionType: '',
        defaultExpandedKeys: [],
        multipleSelection: [],
        dialogRoleFormVisible: false,
        organizationId: '',
        rules: {
          code: [
            {required: true, message: '请输入组织编码', trigger: 'blur'},
            {max: 50, message: '长度不超过50 个字符', trigger: 'blur'}
          ],
          name: [
            {required: true, message: '请输入组织名称', trigger: 'blur'},
            {max: 50, message: '长度不超过50 个字符', trigger: 'blur'}
          ]
        },
      }
    },
    methods: {
      initData() {
        this.listTableData()

        this.treeSearchParam = {}
        this.treeSearchParam.parentId = ''
        this.listTreeData()
      },
      listTreeData() {
        organizationApi.listAllOrganization(this.treeSearchParam, (res) => {
          this.treeData = res
          for (var td of res) {
            this.defaultExpandedKeys.push(td.id)
          }
        }, () => {
        })
      },
      loadChildren(node, resolve) {
        if (node.level === 0) {
          return resolve(this.treeData)
        }
        this.treeSearchParam = {}
        this.treeSearchParam.parentId = node.data.id
        organizationApi.listAllOrganization(this.treeSearchParam, (res) => {
          resolve(res)
        }, () => {
        })
      },
      handleNodeClick(data) {
        this.tableSearchParam = {}
        this.tableSearchParam.parentId = data.id
        this.currentPage = 1
        this.pageSize = 10
        this.listTableData()
      },
      listTableData() {
        organizationApi.listOrganization(this.tableSearchParam, this.currentPage, this.pageSize, (res) => {
          this.tableData = res.list
          this.total = res.total
        }, () => {
        })
      },
      addData() {
        //清空历史值
        this.formData = {
          parentId: '',
          parentPath: '',
          code: '',
          name: '',
          sort: '',
          description: ''

        }
        this.actionType = 'add'
        organizationApi.listAllOrganization({}, (res) => {
          this.allData = res
          this.dialogFormVisible = true
        }, () => {
          this.$refs['ruleForm'].resetFields()
        })
      },
      handleAdd() {
        this.$refs['ruleForm'].validate((valid) => {
          if (valid) {
            this.loading = true
            organizationApi.addOrganization(this.formData, (res) => {
              this.loading = false
              this.dialogFormVisible = false
              this.$message({
                message: '添加成功',
                type: 'success'
              })
              this.initData()
            }, () => {
              this.loading = false
            })
          }
        })
      },
      editData(index, row) {
        //清空历史值
        this.formData = {
          parentId: '',
          parentPath: '',
          code: '',
          name: '',
          sort: '',
          description: ''

        }
        let that = this
        that.actionType = 'edit'
        this.loading = true
        organizationApi.getOrganizationById(row.id, (res1) => {
          organizationApi.listAllOrganization({}, (res2) => {
            that.allData = res2
            that.formData = res1
            that.formData.id = row.id
            this.loading = false
            that.dialogFormVisible = true
          }, () => {
          })
        }, () => {
        })
      },
      handleEdit() {
        this.$refs['ruleForm'].validate((valid) => {
          if (valid) {
            this.loading = true
            organizationApi.updateOrganization(this.formData.id, this.formData, (res) => {
              this.loading = false
              this.dialogFormVisible = false
              this.$message({
                message: '修改成功',
                type: 'success'
              })
              this.initData()
            }, () => {
              this.loading = false
            })
          }
        })
      },
      handleDelete(index, row) {
        this.$confirm('此操作将永久删除该数据, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          organizationApi.deleteSingleOrganization(row.id, (res) => {
            this.$message({
              type: 'success',
              message: '删除成功!'
            })
            this.initData()
          }, () => {
          })
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          });
        });
      },
      handleSizeChange(val) {
        this.pageSize = val
        this.listTableData()
      },
      handleCurrentChange(val) {
        this.currentPage = val
        this.listTableData()
      },
      searchTreeData() {
        this.treeSearchParam = {}
        if (this.treeSearchInputValue == '') {
          this.treeSearchParam.parentId = ''
        } else {
          this.treeSearchParam.name = this.treeSearchInputValue
        }
        this.listTreeData()
      },
      searchTableData() {

      },
      pOrganizationChange(value) {
        this.formData.parentPath = ''
        for (var ad of this.allData) {
          if (ad.id == value) {
            this.formData.parentPath = (ad.parentPath == '' ? '' : ad.parentPath + ',') + value
            break
          }
        }
      },
      handleSelectionChange(val) {
        this.multipleSelection = []
        for (var ms of val) {
          this.multipleSelection.push(ms.id)
        }
      },
      deleteAny() {
        if (this.multipleSelection.length == 0) {
          this.$message({
            type: 'warning',
            message: '请选择记录!'
          })
          return;
        }
        this.$confirm('此操作将永久删除该数据, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          organizationApi.deleteOrganization(this.multipleSelection, (res) => {
            this.$message({
              type: 'success',
              message: '删除成功!'
            })
            this.multipleSelection = []
            this.initData()
          }, () => {
          })
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
      },
      allocateRole(index, row) {
        this.noSelectRole = []
        this.selectRole = []
        const loadings = this.$loading({
          lock: true,
          text: '拼命加载中...',
          spinner: 'el-icon-loading',
          background: 'rgba(0, 0, 0, 0.7)'
        });
        roleApi.listAllRole((res) => {
          this.noSelectRole = res
          organization2roleApi.listRoleSelectd(row.id.split(','), (res) => {
            for (var r of res) {
              this.selectRole.push(r.id)
            }
            this.organizationId = row.id
            this.dialogRoleFormVisible = true
            loadings.close()
          }, () => {
            loadings.close()
          })
        }, () => {
        })
      },
      handleAllocateRole() {
        let param = {
          organizationId: this.organizationId,
          roleIds: this.selectRole
        }
        this.loading = true
        organization2roleApi.updateOrganizationRole(param, (res) => {
          this.loading = false
          this.dialogRoleFormVisible = false
          this.$message({
            message: '角色分配成功',
            type: 'success'
          })
        }, () => {
          this.loading = false
        })
      }
    }
  }
</script>
